package com.estun.backroundManagementService.modules.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.estun.backroundManagementService.aop.operationLog.Log;
import com.estun.backroundManagementService.aop.operationLog.LogConstants;
import com.estun.backroundManagementService.domain.BaseResponse;
import com.estun.backroundManagementService.domain.factoryMes.FactoryMesResponse;
import com.estun.backroundManagementService.domain.factoryMes.request.base.BaseMesRequest;
import com.estun.backroundManagementService.modules.testResult.model.TestResult;
import com.estun.backroundManagementService.modules.testResult.service.TestResultService;
import com.estun.backroundManagementService.modules.workOrder.dto.WorkOrderEntity;
import com.estun.backroundManagementService.modules.workOrder.service.WorkOrderService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yusiocng
 * @date 2023/11/30
 * @description 对外接口
 */
@RestController
@Api(tags = "ApiController", description = "对外开放接口")
@RequestMapping("/api")
@AllArgsConstructor
@Slf4j
public class ApiController {

    private final WorkOrderService workOrderService;
    private final TestResultService testResultService;

    @PostMapping("/MESSYNC_SCHEDULE")
    @Log(module = "工厂MES排程推送", type = LogConstants.INSERT, desc = "工厂MES排程推送")
    public FactoryMesResponse pushWorkOrder(@RequestBody BaseMesRequest<WorkOrderEntity> request) {
        log.info("【工单推送】 接收到参数:{}", request);
        return workOrderService.push(request);
    }

    @PostMapping("/services/app/QM_OfflineRepairRecord/OfflineRepairRecordByFactoryMes")
    @Log(module = "不良品返修信息接口", type = LogConstants.UPDATE, desc = "不良品返修信息接口")
    public FactoryMesResponse OfflineRepairRecordByFactoryMes(@RequestBody BaseMesRequest<JSONObject> request) {
        log.info("【不良品返修信息接口】request:{}", request);
        return FactoryMesResponse.success();
    }

    @PostMapping("/services/app/QM_ProductBase/SNStateByFactoryMes")
    @Log(module = "SN状态调整接口", type = LogConstants.UPDATE, desc = "SN状态调整接口")
    public FactoryMesResponse SNStateByFactoryMes(@RequestBody BaseMesRequest<JSONObject> request) {
        log.info("【SN状态调整接口】request:{}", request);
        return FactoryMesResponse.success();
    }

    /*
     {
        "stationId": "OP080",
        "productNo": "EHS-1234567890",
        "date": "2023-10-20 13-00-00",
        "model": "EHS1",
        "result": "PASS",
        "key1": "工况1_总流量_L/min_10_21_18_OK",
        "key2": "工况1_扭矩_N_0_0.5_0.6_NG"
                工况名_测试项_单位_下限_上限_测试值_结果
    }
    * */
    @PostMapping("/wrap/push")
    public BaseResponse warpPush(@RequestBody JSONObject request) {
        TestResult testResult = new TestResult();
        testResult.setStationId(request.getString("stationId"));
        testResult.setProductNo(request.getString("productNo"));
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
        testResult.setDate(LocalDateTime.parse(request.getString("date"), formatter));
        testResult.setModel(request.getString("model"));
        testResult.setResult(request.getString("result"));

        List<TestResult> res = new ArrayList<>();
        for (String key : request.keySet()) {
            if (key.contains("key")) {
                String valueStr = request.getString(key);
                TestResult buildResult = buildByKey(testResult, valueStr);
                res.add(buildResult);
            }
        }
        if (res.isEmpty()) {
            log.info("推送消息中没有key数据，只保存一条记录:{}", request);
            res.add(testResult);
        }
        boolean b = testResultService.saveBatch(res);
        return b ? BaseResponse.success() : BaseResponse.error("保存失败");
    }

    /**
     * @param valueStr 工况1_扭矩_N_0_0.5_0.6_NG
     *                 工况名_测试项_单位_下限_上限_测试值_结果
     */
    private TestResult buildByKey(TestResult testResult, String valueStr) {
        TestResult buildResult = new TestResult();
        BeanUtils.copyProperties(testResult, buildResult);
        String[] split = valueStr.split("_");
        buildResult.setConditionName(split[0]);
        buildResult.setTestItem(split[1]);
        buildResult.setUnits(split[2]);
        buildResult.setMin(split[3]);
        buildResult.setMax(split[4]);
        buildResult.setValue(split[5]);
        buildResult.setItemResult(split[6]);
        return buildResult;
    }




}
